import axios from 'axios'
import { Message } from 'element-ui'

const request = axios.create({
  baseURL: 'http://127.0.0.1:8888/api/private/v1/',
  timeout: 5000
})

// 请求拦截
request.interceptors.request.use(
  (config) => {
    const tokenStr = window.sessionStorage.getItem('token')
    if (tokenStr) {
      config.headers.Authorization = tokenStr
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 相应拦截
request.interceptors.response.use(
  (response) => {
    const { data: res } = response
    if (res.meta.status !== 200) {
      return Message({
        message: res.meta.msg || '错误',
        type: 'error'
      })
    }
    // Message({
    //   message: res.meta.msg || '成功',
    //   type: 'success'
    // })
    return res
  },
  (error) => {
    return Promise.reject(error)
  }
)

export default request
